package com.cchr.acms.controller;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cchr.acms.model.AbuseType;
import com.cchr.acms.model.AbusedPerson;
import com.cchr.acms.model.Action;
import com.cchr.acms.model.Attorney;
import com.cchr.acms.model.CaseInfo;
import com.cchr.acms.model.CaseInfoQueryEntity;
import com.cchr.acms.model.CaseInfoResult;
import com.cchr.acms.model.DoctorInfo;
import com.cchr.acms.model.Drug;
import com.cchr.acms.model.FacilityInfo;
import com.cchr.acms.model.ReportingPerson;
import com.cchr.acms.service.AbuseTypeService;
import com.cchr.acms.service.AbusedPersonService;
import com.cchr.acms.service.ActionService;
import com.cchr.acms.service.AttorneyService;
import com.cchr.acms.service.CaseInfoService;
import com.cchr.acms.service.DoctorInfoService;
import com.cchr.acms.service.DrugService;
import com.cchr.acms.service.FacilityInfoService;
import com.cchr.acms.service.ReportingPersonService;
import com.cchr.acms.util.DataTableVO;
import com.cchr.acms.util.ListUtil;
import com.cchr.acms.util.PageableDataVO;
import com.cchr.acms.util.HtmlComponentUtil.SelectOption;

@Controller
@RequestMapping("/case")
public class CaseInfoController {
	@Autowired
	private CaseInfoService caseInfoService;
	@Autowired
	private AbusedPersonService abusedPersonService;
	@Autowired
	private ReportingPersonService reportingPersonService;
	@Autowired
	private DrugService drugService;
	@Autowired
	private AbuseTypeService abuseTypeService;
	@Autowired
	private FacilityInfoService FacilityInfoService;
	@Autowired
	private DoctorInfoService doctorInfoService;
	@Autowired
	private AttorneyService attorneyService;
	@Autowired
	private ActionService actionService;
	
	public static String[] COUNTRY = {"Afghanistan","Albania","Algeria","American Samoa","Andorra","Angola","Antigua and Barbuda","Argentina","Armenia","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda","Bhutan","Bolivia","Bosnia and Herzegovina","Botswana","Brazil","Brunei","Bulgaria","Burkina Faso","Burundi","Cambodia","Cameroon","Canada","Cape Verde","Cayman Islands","Central African Republic","Chad","Chile","China","Colombia","Comoros","Congo, Democratic Republic of the","Congo, Republic of the","Costa Rica","Côte d'Ivoire","Croatia","Cuba","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","East Timor","Ecuador","Egypt","El Salvador","Equatorial Guinea","Eritrea","Estonia","Ethiopia","Faroe Islands","Fiji","Finland","France","French Polynesia","Gabon","Gambia","Georgia","Germany","Ghana","Greece","Greenland","Grenada","Guam","Guatemala","Guinea","Guinea-Bissau","Guyana","Haiti","Honduras","Hong Kong","Hungary","Iceland","India","Indonesia","Iran","Iraq","Ireland","Israel","Italy","Jamaica","Japan","Jordan","Kazakhstan","Kenya","Kiribati","North Korea","South Korea","Kosovo","Kuwait","Kyrgyzstan","Laos","Latvia","Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Macedonia","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Marshall Islands","Mauritania","Mauritius","Mexico","Micronesia","Moldova","Monaco","Mongolia","Montenegro","Morocco","Mozambique","Myanmar","Namibia","Nauru","Nepal","Netherlands","New Zealand","Nicaragua","Niger","Nigeria","Northern Mariana Islands","Norway","Oman","Pakistan","Palau","Palestine, State of","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Poland","Portugal","Puerto Rico","Qatar","Romania","Russia","Rwanda","Saint Kitts and Nevis","Saint Lucia","Saint Vincent and the Grenadines","Samoa","San Marino","Sao Tome and Principe","Saudi Arabia","Senegal","Serbia","Seychelles","Sierra Leone","Singapore","Sint Maarten","Slovakia","Slovenia","Solomon Islands","Somalia","South Africa","Spain","Sri Lanka","Sudan","Sudan, South","Suriname","Swaziland","Sweden","Switzerland","Syria","Taiwan","Tajikistan","Tanzania","Thailand","Togo","Tonga","Trinidad and Tobago","Tunisia","Turkey","Turkmenistan","Tuvalu","Uganda","Ukraine","United Arab Emirates","United Kingdom","United States","Uruguay","Uzbekistan","Vanuatu","Vatican City","Venezuela","Vietnam","Virgin Islands, British","Virgin Islands, U.S.","Yemen","Zambia","Zimbabwe"};
	public static String[] DOCTYPE = {"Psychiatrist","Psychologist","General Practitioner","Neurologist", "Pediatrician", "Other Type of MD"};
	public static String[] RELATION = {"Mother","Father","Sister","Brother","Grandparent","Aunt","Uncle","Friend","Other"};
	public static String[] FACILITY_TYPE = {"In-Patient Psychiatric Hospital","Out-Patient Psychiatric Hospital","Private Doctor's Office","Clinic","General Hospital","Nursing Home","School","Other"};
	public static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
	
	@RequestMapping(value={"/create"}, method = RequestMethod.GET)
	public String createPage(HttpServletRequest request){
    	List<Drug> drugs = drugService.getAllDrug();
    	List<SelectOption> datas = new ArrayList<SelectOption>();
    	for(Drug drug : drugs)
    	{
    		SelectOption op = new SelectOption();
    		op.setGroup(drug.getType());
    		op.setLabel(drug.getName());
    		op.setValue(String.valueOf(drug.getId()));
    		datas.add(op);
    	}
    	request.setAttribute("datas", datas);
    	
    	List<SelectOption> countryDatas = new ArrayList<SelectOption>();
    	for (int i = 0; i < COUNTRY.length; i++) {
    		SelectOption op = new SelectOption();
    		op.setLabel(COUNTRY[i]);
    		op.setValue(COUNTRY[i]);
    		countryDatas.add(op);
		}
    	request.setAttribute("countryDatas", countryDatas);
    	
    	List<AbuseType> abuseTypes = abuseTypeService.getAllAbuseType();
    	request.setAttribute("abuseTypes", abuseTypes);
    	
    	List<Action> actions = actionService.getAllAction();
    	request.setAttribute("actions", actions);
    	
    	List<SelectOption> docTypes = new ArrayList<SelectOption>();
    	for (int i = 0; i < DOCTYPE.length; i++) {
    		SelectOption op = new SelectOption();
    		op.setLabel(DOCTYPE[i]);
    		op.setValue(DOCTYPE[i]);
    		docTypes.add(op);
		}
    	request.setAttribute("docTypes", docTypes);
    	
    	List<SelectOption> relations = new ArrayList<SelectOption>();
    	for (int i = 0; i < RELATION.length; i++) {
    		SelectOption op = new SelectOption();
    		op.setLabel(RELATION[i]);
    		op.setValue(RELATION[i]);
    		relations.add(op);
		}
    	request.setAttribute("relations", relations);
    	
    	List<SelectOption> facilityTypes = new ArrayList<SelectOption>();
    	for (int i = 0; i < FACILITY_TYPE.length; i++) {
    		SelectOption op = new SelectOption();
    		op.setLabel(FACILITY_TYPE[i]);
    		op.setValue(FACILITY_TYPE[i]);
    		facilityTypes.add(op);
		}
    	request.setAttribute("facilityTypes", facilityTypes);
        return "case/create";
	}
	
	@RequestMapping(value={"/create"}, method = RequestMethod.POST)
	public String addCase(CaseInfo caseInfo,String[] drugIds,String[] actionsCheckbox,String[] abusetypeCheckbox,HttpSession session) throws ParseException{
		//status:new processing,completed
		String currUser = "admin";
		Date now = new Date();
		caseInfo.setStatus("New");
		caseInfo.setCreatedBy(currUser);
		caseInfo.setLastUpdateDate(now);
		caseInfo.setLastUpdatedBy(currUser);
		
		caseInfo.setTypeIds(ListUtil.ArrayToString(abusetypeCheckbox, ","));
		caseInfo.setDrugIds(ListUtil.ArrayToString(drugIds, ","));
		caseInfo.setActionIds(ListUtil.ArrayToString(actionsCheckbox, ","));
		
		caseInfoService.insertCaseInfo(caseInfo);
		int caseId = caseInfo.getId();
		//先生成caseid
		AbusedPerson abusedPerson = caseInfo.getAbusedPerson();
		abusedPerson.setCaseId(caseId);
		abusedPersonService.insertAbusedPerson(abusedPerson);
		ReportingPerson reportingPerson = caseInfo.getReportedBy();
		reportingPerson.setCaseId(caseId);
		reportingPersonService.insertReportingPerson(reportingPerson);
	 
		int fsize=0; 
		if(caseInfo.getFacilityInfos()!=null&&(fsize = caseInfo.getFacilityInfos().size())>0){
			for (int i = 0; i < fsize; i++) {
				FacilityInfo info = caseInfo.getFacilityInfos().get(i);
				info.setCaseId(caseId);
				FacilityInfoService.insertFacilityInfo(info);
			}
		}
		int dsize = 0;
		if(caseInfo.getDoctorInfos()!=null&&(dsize = caseInfo.getDoctorInfos().size())>0){
			for (int i = 0; i < dsize; i++) {
				DoctorInfo info = caseInfo.getDoctorInfos().get(i);
				info.setCaseId(caseId);
				doctorInfoService.insertDoctorInfo(info);
			}
			
		}

		Attorney attorney = caseInfo.getAttorney();
		attorney.setCaseId(caseId);
		attorneyService.insertAttorney(attorney);
		return "redirect:create/success";
	}
	
	@RequestMapping(value={"/create/success"}, method = RequestMethod.GET)
	public String createSuccessPage() throws ParseException{
		return "/case/create_success";
	}
	
	@RequestMapping(value={"/create/success"}, method = RequestMethod.POST)
	public String createSuccess(String emailAddress) throws ParseException{
		return "redirect:https://www.cchrint.org/";
	}
	
	@RequestMapping(value={"/showAbuseList"}, method = RequestMethod.GET)
	public String showAbuseListDefault(HttpServletRequest request){
		return showAbuseList(request);
	}
	
	@RequestMapping(value={"/showAbuseList"}, method = RequestMethod.POST)
	public String showAbuseList(HttpServletRequest request){
    	List<SelectOption> countryDatas = new ArrayList<SelectOption>();
    	for (int i = 0; i < COUNTRY.length; i++) {
    		SelectOption op = new SelectOption();
    		op.setLabel(COUNTRY[i]);
    		op.setValue(COUNTRY[i]);
    		countryDatas.add(op);
		}
    	request.setAttribute("countryDatas", countryDatas);
    	
    	List<SelectOption> facilityTypes = new ArrayList<SelectOption>();
    	for (int i = 0; i < FACILITY_TYPE.length; i++) {
    		SelectOption op = new SelectOption();
    		op.setLabel(FACILITY_TYPE[i]);
    		op.setValue(FACILITY_TYPE[i]);
    		facilityTypes.add(op);
		}
    	request.setAttribute("facilityTypes", facilityTypes);
    	
    	List<SelectOption> docTypes = new ArrayList<SelectOption>();
    	for (int i = 0; i < DOCTYPE.length; i++) {
    		SelectOption op = new SelectOption();
    		op.setLabel(DOCTYPE[i]);
    		op.setValue(DOCTYPE[i]);
    		docTypes.add(op);
		}
    	request.setAttribute("docTypes", docTypes);
    	
    	
    	List<SelectOption> abuseTypes = new ArrayList<SelectOption>();
    	List<AbuseType> abuseList = abuseTypeService.getAllAbuseType();
    	for (AbuseType abuseType : abuseList) {
    		SelectOption op = new SelectOption();
    		op.setLabel(abuseType.getName());
    		op.setValue(abuseType.getId()+"");
    		abuseTypes.add(op);
		}
    	request.setAttribute("abuseTypes", abuseTypes);
    	
    	return "case/showCase";
	}
	
	@RequestMapping(value={"/showAbuseListJson"}, method = RequestMethod.POST)
    @ResponseBody
    public PageableDataVO<CaseInfoResult> getAbuseList(DataTableVO dataTableVO, CaseInfoQueryEntity queryEntity) {
		//解析
		int index = dataTableVO.getStart();
		int offset = dataTableVO.getLength();
		PageableDataVO<CaseInfoResult> data = new PageableDataVO<CaseInfoResult>();
		List<CaseInfoResult> result = new ArrayList<CaseInfoResult>();
        try {
        	List<CaseInfo> list = caseInfoService.queryAbuseInfo(queryEntity,index,offset);
        	int total = caseInfoService.queryTotal(queryEntity);
        	data.setiTotalDisplayRecords(total);
    		data.setiTotalRecords(total);
        	for (int i = 0; i < list.size(); i++) {
        		AbusedPerson abusedPerson = abusedPersonService.getAbusedPersonByCaseId(list.get(i).getId());
        		list.get(i).setAbusedPerson(abusedPerson);
        		List<DoctorInfo> doctorInfos = doctorInfoService.queryDoctorInfoByCaseId(list.get(i).getId());
        		list.get(i).setDoctorInfos(doctorInfos);
        		List<FacilityInfo> facilityInfos = FacilityInfoService.getFacilityInfoByCaseId(list.get(i).getId());
        		list.get(i).setFacilityInfos(facilityInfos);
        		CaseInfoResult rs = new CaseInfoResult();
        		// mock data
        		rs.setSequence("C" + (Long.valueOf(sdf.format(new Date()))*10000 + i + 1));
        		rs.setProcessedBy("CCHR INT");
        		// mock end
        		rs.setId(list.get(i).getId());
        		//patient name
        		rs.setPatientName(list.get(i).getAbusedPerson().getFirstName());
        		//create time
        		rs.setCreateTime(list.get(i).getCreateDate());
        		//status
        		rs.setStatus(list.get(i).getStatus());
        		rs.setCity(list.get(i).getAbusedPerson().getCity());
        		rs.setLastUpdateDate(list.get(i).getLastUpdateDate());
        		rs.setLastUpdatedBy(list.get(i).getLastUpdatedBy());
        		//doctor name
        		List<DoctorInfo> dlist = list.get(i).getDoctorInfos();
        		StringBuilder sb = new StringBuilder();
        		if(dlist!=null&&(dlist.size()>0)){
        			for (int j = 0; j < dlist.size()-1; j++) {
						sb.append(dlist.get(j).getName()).append(",");
					}
        			sb.append(dlist.get(dlist.size()-1).getName());
        		}
        		rs.setDoctorName(sb.toString());
        		
        		//facility name
        		List<FacilityInfo> flist = list.get(i).getFacilityInfos();
        		sb = new StringBuilder();
        		if(flist!=null && flist.size()>0){
        			for (int j = 0; j < flist.size() - 1; j++) {
						sb.append(flist.get(j).getName()).append(",");
					}
        			sb.append(flist.get(flist.size()-1).getName());
        		}
        		rs.setFacilityName(sb.toString());
        	
        		result.add(rs);
			}
        	data.addData(result);
            return data;

        } catch (Exception e) {
        	e.printStackTrace();
            return data;
        }
    }

	
	@RequestMapping(value={"/detail/{id}"}, method = RequestMethod.GET)
	public String detailPage(HttpServletRequest request, @PathVariable Integer id)
	{
		if(id != null)
		{
			CaseInfo caseInfo = caseInfoService.getCaseInfoById(id);
			if(caseInfo != null)
			{
				AbusedPerson abusedPerson = abusedPersonService.getAbusedPersonByCaseId(id);
				caseInfo.setAbusedPerson(abusedPerson);
				ReportingPerson reportingPerson = reportingPersonService.getReportingPersonByCaseId(id);
				caseInfo.setReportedBy(reportingPerson);
				Attorney attorney = attorneyService.getAttorneyByCaseId(id);
				caseInfo.setAttorney(attorney);
				List<DoctorInfo> doctorInfos = doctorInfoService.queryDoctorInfoByCaseId(id);
				caseInfo.setDoctorInfos(doctorInfos);
				List<FacilityInfo> facilityInfos = FacilityInfoService.getFacilityInfoByCaseId(id);
				caseInfo.setFacilityInfos(facilityInfos);
				
				String typeIds = caseInfo.getTypeIds();
				if(typeIds != null)
				{
					StringBuilder sb = new StringBuilder();
					String[] typeIdArr = typeIds.split(",");
					if(typeIdArr.length > 0)
					{
						List<String> typeIdList = Arrays.asList(typeIdArr);
						List<AbuseType> abuseTypes = abuseTypeService.getAllAbuseType();
				    	for(AbuseType type : abuseTypes)
				    	{
				    		if(typeIdList.contains(String.valueOf(type.getId())))
				    		{
				    			sb.append(type.getName()).append(", ");
				    		}
				    	}
					}
					if(sb.lastIndexOf(",") == sb.length() - 2)
					{
						sb.delete(sb.length() - 2, sb.length());
					}
					request.setAttribute("typeIds", sb.toString());
				}
				
				String drugIds = caseInfo.getDrugIds();
				if(drugIds != null)
				{
					String[] drugIdArr = drugIds.split(",");
					if(drugIdArr.length > 0)
					{
						List<String> drugIdList = Arrays.asList(drugIdArr);
						List<Drug> drugs = drugService.getAllDrug();
						List<String> drugNames = new ArrayList<String>();
				    	for(Drug drug : drugs)
				    	{
				    		if(drugIdList.contains(String.valueOf(drug.getId())))
				    		{
				    			drugNames.add(drug.getName());
				    		}
				    	}
				    	request.setAttribute("drugNames", drugNames);
					}
				}
				
				String actionIds = caseInfo.getActionIds();
				if(actionIds != null)
				{
					String[] actionIdArr = actionIds.split(",");
					if(actionIdArr.length > 0)
					{
						List<String> actionIdList = Arrays.asList(actionIdArr);
						List<Action> actions = actionService.getAllAction();
						List<String> acs = new ArrayList<String>();
				    	for(Action action : actions)
				    	{
				    		if(actionIdList.contains(String.valueOf(action.getId())))
				    		{
				    			acs.add(action.getName());
				    		}
				    	}
				    	request.setAttribute("actions", acs);
					}
				}
			}
			System.out.println(caseInfo);
			request.setAttribute("caseInfo", caseInfo);
		}
    	
        return "case/detail";
	}
	
	
	@org.springframework.web.bind.annotation.InitBinder
	public void InitBinder(WebDataBinder dataBinder)
	{
		dataBinder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
		    public void setAsText(String value) {
		        try {
		            setValue(new SimpleDateFormat("MM/dd/yyyy").parse(value));
		        } catch(ParseException e) {
		            setValue(null);
		        }
		    }

		    public String getAsText() {
		        return new SimpleDateFormat("MM/dd/yyyy").format((Date) getValue());
		    }        

		});
	}
	
}
